﻿#ifndef MODEBUSDEVICE_H
#define MODEBUSDEVICE_H
#include <QList>
#include <QString>
#include <QTimer>
#include <QMutex>
#include <QThread>

#include "../libmodbus/modbus.h"
#include "BaseCommunication.h"

class BaseModbus :public BaseCommunication
{
    Q_OBJECT
public:
    explicit  BaseModbus(QObject *parent=nullptr);
    ~BaseModbus();
    bool ReadOutRegister(int addr,uint16_t &ret);

    bool ReadInRegister(int addr,uint16_t &ret);

    virtual bool ReadOutRegisters(int addr, int count, QList<uint16_t> &retList);
    virtual bool ReadInRegisters(int addr, int count, QList<uint16_t> &retList);

    bool WriteRegister(int addr, uint16_t input);
    virtual bool WriteRegisters(int addr, int count, QList<uint16_t> inputList);
    virtual bool ReadInBits(int addr, int count, QList<bool> &retList);
    virtual bool ReadOutBits(int addr, int count, QList<bool> &retList);
    virtual bool WriteBits(int addr, int count, QList<bool> inputList);
    bool DisConnect();

    virtual void CreateModbusInstance()=0;

    //BaseCommunication
    bool IsConnected() override;
    bool Connect() override;
    void Dispose() override;

protected:
    virtual void AutoReconnect();

public:
    template<typename T>
    static void SConvert(T *source,int size, QList<T> &target)
    {
        for (int i = 0; i < size; i++)
        {
            target.append(source[i]); // 逐个添加元素到 QList 中
        }
    }


public slots:

private:
    bool _isConnected;
    bool _isRunning=true;
    QMutex  _mutex;   //可以是私有成员变量，也可以是全局变量
    bool _isFirstConnect=true;
protected:
    modbus_t *m_ctx;
};

#endif // MODEBUSDEVICE_H
